//
//  ViewController.swift
//  CAGradientLayer
//
//  Created by 李煜 on 2023/3/13.
// https://www.cnblogs.com/sunyanyan/p/5359589.html

import UIKit

class ViewController: UIViewController {
  let gradientLayer: CAGradientLayer = .init()
  lazy var timer: Timer = {
    let time = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerEvent), userInfo: nil, repeats: true)
    return time
  }()

  override func viewDidLoad() {
    super.viewDidLoad()

    // 初始化imageView
    let imageView = UIImageView(image: UIImage(named: "login_logo"))
    imageView.frame = .init(x: 0, y: 0, width: view.bounds.width, height: 200)
    imageView.center = view.center
    view.addSubview(imageView)

//    初始化渐变层
    gradientLayer.frame = imageView.bounds
    imageView.layer.addSublayer(gradientLayer)

//    设置渐变方向
    gradientLayer.startPoint = .init(x: 0, y: 0)
    gradientLayer.endPoint = .init(x: 0, y: 1)

//    设置颜色组
    gradientLayer.colors = [UIColor.clear.cgColor,
                            UIColor.purple.cgColor]
//    设置颜色分割点
    gradientLayer.locations = [0.5, 1.0]

//    定时器
    timer.fire()
  }

  @objc func timerEvent() {
//    定时器改变颜色
    gradientLayer.colors = [UIColor.clear.cgColor,
                            UIColor(red: Double.random(in: 1...255) / 255.0, green: Double.random(in: 1...255) / 255.0, blue: Double.random(in: 1...255) / 255.0, alpha: 1).cgColor]
//    gradientLayer.locations = [NSNumber(value: Double(arc4random() % 10) / 10.0), 1.0]

    gradientLayer.locations = [NSNumber(value: Double(arc4random_uniform(10)) / 10.0),
                               1.0]
//    var result = arc4random() % 10
    var result = arc4random_uniform(10)
    print("... " + result.description)
  }
}
